angular.module('UCX.Cmis')
.controller 'CreateFolderCtrl', ($scope, $uibModalInstance,Utils,$translate)->
  $scope.folderName = ''
  $scope.handleEnterKey=(e)->
    if e.which==13
      $scope.ok()
  $scope.ok = ()->
    if Utils.containIllegalChar($scope.folderName)
      $translate('641').then(
        (result)->
          result = result.replace('&lt;','<').replace('&gt;','>')
          Utils.warning(result)
      ,
        ()->)
      return
    if $scope.folderName.length==0
      $translate('folder_name_null').then (text)->
        Utils.warning(text)
      return
    $uibModalInstance.close($scope.folderName)
  $scope.cancel = ()->
    $uibModalInstance.dismiss('cancel')

.controller "UploadDrnCtrl", ($scope, $uibModalInstance, dropFile, Loading, CmisService, folder, Utils, $translate, parentScope, $timeout,UploadQueue)->
  $scope.tempFolder = $scope.currentFolder
  $scope.dropFile = dropFile
  $scope.file = dropFile
  $scope.freePreviewPages = 3
  $scope.ok = ()->
    file = if dropFile then dropFile else $scope.file
    ext = Utils.getFileExt(file.name)
    if !Utils.isAllowExtension(file)
      $translate('file_type_error').then (text)->
        Utils.warning(text)
      return false
    freePreviewPages = $scope.freePreviewPages
    UploadQueue.add(
      file,
      $scope.tempFolder.id,
      {
      'cmis:name': file.name,
      'cmis:objectTypeId': 'smx:drmdoc'
      'smxj:freePreviewPages': parseInt(freePreviewPages)
      },
      "none"
    )
    $uibModalInstance.close({file:$scope.file, freePreviewPages:$scope.freePreviewPages})
  $scope.cancel = ()->
    $uibModalInstance.dismiss('cancel')

  $scope.isDisabled = ()->
    !$scope.file || $scope.freePreviewPages < 0

.controller "createInviteModal", ($scope, $uibModalInstance, isOwner, document, sendToOwner, sending, Utils, CmisService, ModelService)->
  $scope.isOwner=isOwner
  $scope.document=document
  $scope.sending=sending
  $scope.sendToOwner=sendToOwner
  $scope.newEmail=''
  $scope.emails=[]
  $scope.emailPattern=/^[a-zA-Z0-9!#$%&'*+\/=?^_`{|}~-]+(?:\.[a-zA-Z0-9!#$%&'*+\/=?^_`{|}~-]+)*@(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?\.)+[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$/
#  $scope.deleteArrayItem=(arr,index)->
#    rest=arr.arr.slice(index + 1 || arr.length)
#    arr.length = index < 0 ? arr.length + index : index
#    arr.push.apply(arr, rest)
  $scope.delete=(index)->
    $scope.emails.splice(index,1)
  $scope.addNewEmail=()->
    isValidEmail=$scope.emailPattern.test($scope.newEmail)
    isEmailEmpty=$scope.newEmail==''
    if(isValidEmail)
      $scope.emails.push({id:$scope.id,emailAddress:$scope.newEmail})
      $scope.newEmail=''
    else if !isValidEmail&&!isEmailEmpty
      Utils.warning "Invalid Email"
    else if isEmailEmpty
      Utils.warning "Email Not Null"
  $scope.getEmailList = ()->
    emailList = []
    for email in $scope.emails
      if email.emailAddress != ''
        emailList.push email.emailAddress
    if $scope.newEmail != ''
      emailList.push $scope.newEmail
    emailList
  $scope.isValid = ()->
    emailList = $scope.getEmailList()
    isValid = if emailList.length then true else false
    for email in emailList
      if !$scope.emailPattern.test(email)
        isValid = false
    isValid
  $scope.ok=()->
    token=CmisService.token
    postUrl=CmisService.baseUrl+'api/v3/room/request-access?access-token='+token
    #emailList 是推入下方的 那个 email的表
    documentId = if document then document.id else ''
    roomId=ModelService.getRoomId()
    isValid = $scope.isValid()
    if isValid
      emailList = $scope.getEmailList()
      postData={
        rid:roomId
        did:documentId
        invitee_list:emailList
        message_to_owner:$scope.message
      }
      $.ajax(
        {
          type:'POST'
          url:postUrl,
          data:postData,
          dataType:'json',
          success:()->
            Utils.success "Success!"
            $uibModalInstance.close()
          error:(data)->
            jsonData = JSON.parse(data.responseText)
            Utils.warning jsonData.message
            $scope.sending=false
            $scope.sendToOwner=sendToOwner
        }
      )
      $scope.sending=true
      $scope.sendToOwner='Sending'
    else
      Utils.warning "Invalid Email"
  $scope.cancel=()->
    $uibModalInstance.dismiss('cancel')
.controller "RenameCtrl", ($scope, $uibModalInstance,CmisService,file,$timeout,Utils,$rootScope,$translate,scope)->
  $scope.repository = CmisService.repository=='fxcld'
#  $uibModalInstance.opened 是一个promise类 那么就有promise类的属性
  $scope.file = file
  #  $scope.oldName 存储原来的名字
  $scope.oldName = file.name
  #  $scope.newName 作为双向绑定变量
  $scope.newName = file.name
  CmisServiceSession = CmisService.session
  # 打开会直接focus
  $scope.ok = ()->
    if $scope.newName.length==0
      $translate('folder_name_null',).then (text)->
        Utils.warning(text)
      return
    if Utils.containIllegalChar($scope.newName)
      $translate('641').then(
        (result)->
          result = result.replace('&lt;','<').replace('&gt;','>')
          console.log(result)
          Utils.warning(result)
      ,
        ()->)
      return
    if $scope.newName != $scope.oldName
#      立刻马上显示结果不等待结果
      file.name = $scope.newName
      url = CmisServiceSession.defaultRepository.rootFolderUrl+'?objectId='+file.id
      postData = {
        'propertyId[0]':'cmis:name'
        'propertyValue[0]':$scope.newName
        'cmisaction':'update'
        'succinct':'true'
      }
      $.ajax(
        {
          type: 'POST'
          url:url,
          beforeSend: (request)->
            request.setRequestHeader("Authorization", 'Bearer ' + CmisService.token)
          data: postData
          success: (data)->
            $translate('rename_succ',).then (text)->
              Utils.success(text)
            Utils.showFilenameTooltip(file)
            if file.isDocument()
#         更新版本 以及自己的id
#          file.getVersions(null,null,true)
              parent = file.getParent()
              Utils.sendGaEvent("Document", "Rename", file.id)
              file.createActivity "update-document", {name: $scope.newName}
            else
              scope.updateLeftAsideFolderTree()
              file.path = data.succinctProperties['cmis:path']
              Utils.sendGaEvent("Folder", "Rename", file.id)
              file.createActivity "modify-folder", {name: $scope.newName}
          error: (r)->
            file.name = $scope.oldName
            newPath = $scope.file.getParent().path+'/'+$scope.newName
            #            console.log(r.responseJSON)
            console.log(r.responseJSON)
            $scope.file.path.lastIndexOf('')
            Utils.translateErrorMsg(r.responseJSON,{path:newPath})
        }
      )

    #      CmisServiceSession.updateProperties(
    #        file.id,
    #        {'cmis:name':$scope.newName}
    #      ).notOk (r)->
    #        file.name = $scope.oldName
    #        jsonData = JSON.parse(r.text)
    #        Utils.warning(jsonData.message)
    #      .ok (data)->
    #        Utils.showFilenameTooltip(file)
    #        if file.isDocument()
    ##         更新版本 以及自己的id
    ##          file.getVersions(null,null,true)
    #          parent = file.getParent()
    #          file.createActivity "update-document", {name: $scope.newName}
    #        else
    #          file.path = data.succinctProperties['cmis:path']
    #          file.createActivity "modify-folder", {name: $scope.newName}
    $uibModalInstance.close()
  #  enter button 相当于执行了 ok
  $scope.handleEnterKey=(e)->
    if e.which==13 && $scope.newName.length>0
      $scope.ok()
  $scope.cancel = ()->
    $uibModalInstance.dismiss('cancel')
  #  部分选择 文件名
  $scope.rangeSelect=(textField,start,end)->
#    textField 可以是 document.getElementById('text') 也可以是 $('#text') 是一个对象
#    start 表示的是 文字高亮的起始点 但是不包含该点
#    end   表示  文字高亮区的结束点  包含
    if textField.createTextRange
#   ie and opera
      selRange = field.createTextRange()
      selRange.collapse(true)
      selRange.moveStart('character', start)
      selRange.moveEnd('character', end)
      selRange.select()
      textField.focus()
    else if textField.setSelectionRange
#      chrome firefox safari
      textField.focus()
      textField.setSelectionRange(start, end)
    else if typeof textField.selectionStart != 'undefined'
#      if not support
      textField.selectionStart = start
      textField.selectionEnd = end
      textField.focus()
  #      只有当 input框的内容出现时候 才去执行 操作
  $scope.domReady=()->
    if !($('#file-name')[0] && $('#file-name')[0].value)
      $timeout(()->
        $scope.domReady()
      ,300)
    else
      startIndex=0
      endIndex=$scope.oldName.lastIndexOf('.')
      if endIndex==-1
        endIndex=$scope.oldName.length
      $scope.rangeSelect($('#file-name')[0],startIndex,endIndex)
  $uibModalInstance.opened.then(()->
#    这个地方配合 html5 的autofocus 使用 因为 源码modal.js 有 autofocus的操作有时候会导致 选中出问题
    if CmisService.repository == 'fxcld'
      return
    $scope.domReady()
  )
.controller "LoadingController", ($scope, content)->
  $scope.content = content
.controller 'ConfirmController', ($scope, $uibModalInstance, content, title, confirmBtnText, cancelBtnText, $translate) ->
  $scope.content = content
  $scope.confirmTitle = title || $translate.instant('confirm')
  $scope.confirmBtnText = confirmBtnText || $translate.instant('ok')
  $scope.cancelBtnText = cancelBtnText || $translate.instant('cancel')
  $scope.ok = ()->
    $uibModalInstance.close()
  $scope.cancel = ()->
    $uibModalInstance.dismiss('cancel')
.controller 'uploadNewVersionCtrl',($scope, $uibModalInstance , parentScope ,rootScope,$translate, Utils, CmisService , Loading,UploadQueue, content)->
  $scope.content=content
  $scope.confirmTitle = $translate.instant('confirm')
  $scope.confirmBtnText = $translate.instant('ok')
  $scope.cancelBtnText = $translate.instant('cancel')
  CmisServiceSession=CmisService.session
  $scope.rootScope=parentScope
#  console.log parentScope
  $scope.ok = ()->
    $translate('uploading').then (text)->
      if rootScope.progressHandler
        rootScope.progressHandler.dismiss()
        UploadQueue.modal=false
      Loading.open text

    console.log parentScope.modifyNewFile
    parentScope.setContentStream(parentScope.modifyNewFile)
    $uibModalInstance.close()
    return
#
#    if parentScope.tempFile.isVersionSeriesCheckedOut
#      parentScope.checkIn(parentScope.modifyNewFile)
#    else
#      CmisServiceSession.checkOut(parentScope.tempFile.id).ok (checkOutObj)->
#        parentScope.checkIn(parentScope.modifyNewFile)
#      .notOk (r)->
#        if Utils.handleCmis401Error(r)
#          return
#        Utils.isUploadNewVersioning = false
#        Loading.close()
#        jsonData = JSON.parse(r.text)
#        Utils.warning(jsonData.message)
#    $uibModalInstance.close()
  $scope.cancel = ()->
    $uibModalInstance.dismiss('cancel')
.controller 'userNotAllowedUpload',($scope,$uibModalInstance)->
  $scope.ok=()->
    $uibModalInstance.close()
.controller "moveToFolderModal", ($scope, $uibModalInstance, files, currentFolder, CmisService, Utils,ModelService,$rootScope,$translate,scope)->
  CmisServiceSession = CmisService.session
  $scope.selected = null
  $scope.currentFolder = currentFolder
  $scope.destFolder = currentFolder
  $scope.moveTargetId = ''
  objectIds = []
  for file in files
    objectIds.push(file.id)
  if files.length==1 && !files[0].isDocument()
    $scope.moveTargetId = files[0].id
  $scope.totalMovedItemNum = files.length
  $scope.successMoveCount = 0
  $scope.failedMoveCount = 0
  $scope.enterIn = (folder)->
    $scope.destFolder = folder
    $scope.isDisabled()
  $scope.backOf = (folder)->
    parentFolder = folder.getParent()
    console.log(parentFolder)
    $scope.destFolder = parentFolder
    $scope.isDisabled()
  successCallback=(objectId, sourceFolder, targetFolder,lastErr)->
    if !lastErr
      $scope.successMoveCount++

    if $scope.successMoveCount + $scope.failedMoveCount == $scope.totalMovedItemNum
      if $scope.successMoveCount == 1
        $translate('one_move_success').then((result)->
          Utils.success(result)
        )
      else
        if $scope.successMoveCount ==0
          return false
        else
          $translate('more_move_success',{
            successNum:$scope.successMoveCount
          }).then((result)->
            Utils.success(result)
          )
    if lastErr
      return false
    else
      file = ModelService.getObjectById(objectId)
      file.refresh()
      if !file.isDocument()
        if currentFolder.id == sourceFolder.id
          sourceFolder=currentFolder
        if sourceFolder.folderList&&sourceFolder.folderList.length
          index = i for folder,i in sourceFolder.folderList when file.id == folder.id
          sourceFolder.folderList.splice(index,1)
        #              和下面同样的问题 空文件夹 移入的时候会报错
        if !targetFolder.folderList
          targetFolder.folderList=[]
        targetFolder.folderList.push file

        file.loadChildren = false
        file.folderList = null
        file.children = []
        Utils.sendGaEvent("Folder", "Move", file.id)
        file.createActivity "move-folder", {name: file.name, from_folder_name: sourceFolder.name, to_folder_name: targetFolder.name}
      else
        Utils.sendGaEvent("Document", "Move", file.id)
        file.createActivity "move-document", {name: file.name, from_folder_name: sourceFolder.name, to_folder_name: targetFolder.name}

      index = i for folder,i in sourceFolder.children when file.id == folder.id
      sourceFolder.children.splice(index,1)
      #            新创建的文件夹 移入文件会报错
      if !targetFolder.children
        targetFolder.children=[]
      targetFolder.children.push(file)
      scope.multipleChooseFiles=[]
      scope.choseFile=scope.currentFolder
      scope.scopeApply(500)
  $scope.isDisabled=()->
    currentFolder.path == $scope.destFolder.path || !$scope.destFolder.allowableActions.canCreateFolder || !$scope.destFolder.allowableActions.canCreateDocument  || objectIds.indexOf($scope.destFolder.id)>-1 || $scope.destFolder.isReadonly()
  $scope.ok=()->
#    处理 移动事件
    delay=1
    sourceFolder=currentFolder
    targetFolder=$scope.destFolder
    targetId = $scope.destFolder.id
    sourceId = currentFolder.id
    ajaxcall = (objectId)->
      sourceId = ModelService.getObjectById(objectId).getParent().id
      options = {}
      options.objectId = objectId
      options.cmisaction = 'move'
      options.targetFolderId = targetId
      options.sourceFolderId = sourceId
      $.ajax(
        {
          type: 'POST'
          url:CmisService.session.defaultRepository.rootFolderUrl,
          beforeSend: (request)->
            request.setRequestHeader("Authorization", 'Bearer ' + CmisService.token)
          data: options
          success: ()->
            movedObj=ModelService.getObjectById(objectId)
            sourceFolder=movedObj.getParent()
            successCallback(objectId, sourceFolder, targetFolder)
          error: (r)->
            $scope.failedMoveCount++
            if $scope.failedMoveCount+$scope.successMoveCount==$scope.totalMovedItemNum
              successCallback(objectId, currentFolder, sourceFolder, targetFolder,true)
            path = ModelService.allFiles[targetId].path + '/' + ModelService.allFiles[objectId].name
            console.log(r.responseJSON)
            return scope.translateErrorMsg(r.responseJSON, {
              path: path
            })
        }
      )
    for objectId in objectIds
      setTimeout((objectId)->
        ajaxcall(objectId)
      ,delay*300,objectId)
      delay++
    $uibModalInstance.close()

  $scope.cancel=()->
    $uibModalInstance.dismiss()

.controller 'deleteModal', ($scope,$uibModalInstance,files,CmisService,currentFolder,ModelService,Utils,$rootScope,$q,$translate, $timeout, scope, searchModeIsOn)->
  CmisServiceSession = CmisService.session
  $scope.pathIsLoading = if files.length == 1 then true else false
  $scope.files=files
  $scope.hasFolders= true for file in files when !file.isDocument()
  $scope.hasDocs= true for file in files when file.isDocument()

  if $scope.pathIsLoading
    $scope.pathIsLoading = false
#    if !files[0].isDocument()
#      $scope.pathIsLoading = false
#    else
#      if files[0].getPaths
#        files[0].getPaths((success)->
#          console.log success
#          $scope.pathIsLoading = false
#        ,
#          (error)->
#            console.log(error)
#            $rootScope.translateErrorMsg(error)
#        )
#      else
#        $scope.pathIsLoading = false


  $scope.currentFolder=currentFolder
  $scope.allFiles=ModelService.allFiles

  $scope.successDeleteFileNumber=0
  $scope.unDeleteFileNumber=0
  $scope.isNeedDeleteSuccessCallback=()->
    if $scope.successDeleteFileNumber+$scope.unDeleteFileNumber==$scope.totalDeleteNum && $scope.successDeleteFileNumber!=0
      if $scope.successDeleteFileNumber==1
        num=$scope.successDeleteFileNumber
        #        successCallbackMSG=$scope.successDeleteFileNumber+' file removed'
        $translate('one_file_remove',{num:num}).then (text)->
          Utils.success(text)
      else
        num=$scope.successDeleteFileNumber
        #        successCallbackMSG=$scope.successDeleteFileNumber+' files removed'
        $translate('multi_files_remove',{num:num}).then (text)->
          Utils.success(text)
      scope.multipleChooseFiles = []
      #      $scope.getChildren($scope.currentFolder)
      scope.choseFile = $scope.currentFolder
      $scope.successDeleteFileNumber=0
      $scope.unDeleteFileNumber=0
#      scope.updateLeftAsideFolderTree()
#      $timeout(()->
#        $rootScope.$apply()
#      ,0)
  deleteFolder=(folderForDel)->
    if !folderForDel.allowableActions.canDeleteObject
      warningMsg='You do not have permission to delete this Folder '+folderForDel.name
      $scope.unDeleteFileNumber++
      $scope.isNeedDeleteSuccessCallback()
      Utils.warning(warningMsg)
    else
      parent = folderForDel.getParent()
      CmisServiceSession.deleteTree(folderForDel.id, true)
      .ok ()->
      # absolute parent
        # folder tree
        index = i for folder,i in parent.folderList when folderForDel.id == folder.id
        parent.folderList.splice(index,1)
        # children
        index = i for folder,i in parent.children when folderForDel.id == folder.id
        if index!=-1
          parent.children.splice(index,1)
      # relative parent
        if searchModeIsOn
          relaPare = $scope.currentFolder
          index = i for folder,i in relaPare.children when folderForDel.id == folder.id
          relaPare.children.splice(index,1)
        scope.choseFile = $scope.currentFolder
        parent.createActivity "delete-folder", {name: folderForDel.name,from_folder_name:parent.name, del_id:folderForDel.id}
        $scope.successDeleteFileNumber++
        $scope.isNeedDeleteSuccessCallback()
      .notOk (r)->
        if Utils.handleCmis401Error(r)
          return
        jsonData = JSON.parse(r.text)
        $scope.unDeleteFileNumber++
        $scope.isNeedDeleteSuccessCallback()
        scope.translateErrorMsg(jsonData)
  #        Utils.warning(jsonData.message)
  deleteFile=(document,allVersionCount)->
    if !document.allowableActions.canDeleteObject
      warningMsg='You do not have permission to delete this Folder '+document.name
      $scope.unDeleteFileNumber++
      $scope.isNeedDeleteSuccessCallback()
      Utils.warning(warningMsg)
    else
      CmisServiceSession.deleteObject(document.id, true)
      .ok ()->
      # absolute parent
        absoluteParent = document.getParent()
        index = i for tempFile,i in absoluteParent.children when document.id == tempFile.id
        absoluteParent.children.splice(index,1)
      # relative parent
        if searchModeIsOn
          parent = $scope.currentFolder
          index = i for tmp,i in parent.children when tmp.id == document.id
          #        console.log('deleteFile',index)
          if index!=-1
            parent.children.splice(index,1)
        if allVersionCount
#          删单个多重归档，全选的时候
          $scope.successDeleteFileNumber+=allVersionCount
        else
          $scope.successDeleteFileNumber++
        #        console.log('delete方法',$scope.successDeleteFileNumber)
        $scope.choseFile = $scope.currentFolder
        $scope.isNeedDeleteSuccessCallback()
        absoluteParent.createActivity "delete-document", {name: document.name,from_folder_name:absoluteParent.name, del_id:document.id}
#        $scope.currentFolder.getChildren $scope, ()->
#          $scope.children = $scope.currentFolder.children
#          $scope.multipleChooseFiles = []
#          $scope.choseFile = $scope.currentFolder
#          document.createActivity "delete-document", {name: document.name,from_folder_name:parent.name}
#        ,
#          null
#        ,
#          true
      .notOk (r)->
        if Utils.handleCmis401Error(r)
          return
        jsonData = JSON.parse(r.text)
        $scope.unDeleteFileNumber++
        $scope.isNeedDeleteSuccessCallback()
        scope.translateErrorMsg(jsonData)
  #        Utils.warning(jsonData.message)
  removeFromFolder=(file,folderId)->
    options = {}
    options.succinct=true
    options.objectId = file.id
    options.cmisaction = 'removeObjectFromFolder'
    options.folderId = folderId
    $.ajax(
      {
        type: 'POST'
        url:CmisService.session.defaultRepository.rootFolderUrl,
        beforeSend: (request)->
          request.setRequestHeader("Authorization", 'Bearer ' + CmisService.token)
        async: false
        data: options
        success: ()->
#          $scope.currentFolder.id 全局变量
          if folderId == $scope.currentFolder.id
            parent=$scope.currentFolder
            index = q for tmp,q in parent.children when tmp.id == file.id
            if index!=-1
              parent.children.splice(index,1)
          if parent
            $scope.choseFile = $scope.currentFolder
          folder=ModelService.allFiles[folderId]
          file.createActivity "remove-document", {name: file.name,from_folder_name:folder.name}
          $scope.successDeleteFileNumber++
          $scope.isNeedDeleteSuccessCallback()
        error: (r)->
          scope.translateErrorMsg(r.responseJSON)
          $scope.unDeleteFileNumber++
          $scope.isNeedDeleteSuccessCallback()
      }
    )
  totalDeleteCount=(files)->
    $scope.totalDeleteNum=0
#    if files.length>1
    $scope.totalDeleteNum=files.length
#    else
##      多重归档file 和 非多重file 处理
#      if files[0].isDocument()
#        if files[0].paths && files[0].paths.length>1
#          if i.paths.length == $('ul[data-id="'+i.id+'"] :checked').length
#            $scope.totalDeleteNum+=1
#          else
#          $scope.totalDeleteNum += $('ul[data-id="'+files[0].id+'"] :checked').length
#        else
#        $scope.totalDeleteNum=1
#      else
#        $scope.totalDeleteNum=1
    $scope.totalDeleteNum
  deleteController=(files)->
    if files.length>1
      for i in files
        if i.isDocument()
#          if i.paths.length>1
#            removeFromFolder(i,currentFolder.id)
#          else
          deleteFile(i)
        else
          deleteFolder(i)
    else
      if files[0].isDocument()
#        if files[0].paths && files[0].paths.length>1
#          removedFolderId=[]
#          folderIds = $('ul[data-id="'+files[0].id+'"] :checked')
#          for q in folderIds
#            removedFolderId.push(q.getAttribute('data-id'))
#          if removedFolderId.length==files[0].paths.length
#            deleteFile(files[0],files[0].paths.length)
#          else
#            for folderId in removedFolderId
#              removeFromFolder(files[0],folderId)
#        else
        deleteFile(files[0])
      else
        deleteFolder(files[0])
  $scope.isDisabled = ()->
    $scope.pathIsLoading

  $scope.ok = ()->
    totalDeleteCount(files)
    deleteController(files)
    $uibModalInstance.close($scope.folderName)
  $scope.cancel = ()->
    $uibModalInstance.dismiss('cancel')
.controller "createProgressBarModal", ($scope, $uibModalInstance ,rootScope, queueFiles,UploadQueue)->
#  expose a progressHandler we can close it by dismiss()
  rootScope.progressHandler=$uibModalInstance
  $scope.files = queueFiles
  $scope.isUploading = ()->
    UploadQueue.uploading
  $scope.isBarOpen = ()->
    UploadQueue.barIsOpen
  $scope.toggleQueue=()->
    $('#progress-bar').toggle(300)
    UploadQueue.barIsOpen = !UploadQueue.barIsOpen
    $scope.isBarOpen()
#    $scope.$apply()
#    return true can solve angular problem ,angularJS does not allow us manipulate dom directly,without this 'return true' it will call a throw error
#    return true
  $scope.ok=()->
  $scope.cancel=()->
    $uibModalInstance.dismiss()
    UploadQueue.queueFiles = []
    UploadQueue.modal=false
.controller 'advancedSearchModal', ($scope,Utils,$translate, $uibModalInstance,chosenOptions,$filter,location,scope)->
  chosenArr = []
  if !chosenOptions
    chosenOptions = {}
    chosenOptions.after = {}
  else
    for type,arg of chosenOptions
      $scope[type]=arg
      if chosenArr.indexOf(type)==-1
        chosenArr.push(type)

  $scope.setTypeAndArg=(arg,type,dateOffset)->
    if chosenArr.indexOf(type)==-1
      chosenArr.push(type)
    if $scope[type]==arg
      $scope[type]=''
      chosenOptions[type]=''
      chosenOptions['after'][type]=''
    else
      $scope[type]=arg
      chosenOptions[type]=arg
      if typeof dateOffset=='number'
        z = $filter('date')(new Date().getTime() - dateOffset * 86400000, 'yyyy-MM-dd')
        chosenOptions['after'][type]=z
  $scope.reset = ()->
    chosenOptions = {}
    chosenOptions.after = {}
    # file name is special
    $scope.fileName=''

    if chosenArr.length==0
      return
    else
      for type in chosenArr
        $scope[type]=''
  getValue =(obj,key)->
    # 防止对象不存在报错
    if obj && obj[key]
      return obj[key]
    else
      ''
  constructSentence = (key,value)->
    if value
      return ''+key+'='+value+'&'
    else
      return ''

  $scope.search=()->
    chosenOptions['fileName']=$scope.fileName
    if chosenOptions['fileName']
      if Utils.sqlContainIllegalChar(chosenOptions['fileName'])
        $translate('contain_illegal_char').then((result)->
          Utils.warning(result)
        )
        return

#   default sentence
    sentence = 'type=document&'

#   也是 url 上面 显示的
#   暴露的数据 title -> fileName
#             lastModificationDateAfter -> lastModificationDateAfter
    #         lastAddedDateAfter -> lastAddedDateAfter
    #         lastViewedDateAfter -> lastViewedDateAfter
#             fileMineType -> fileMineType
#             fileAddedByDevice -> fileAddedByDevice

    title = getValue(chosenOptions,'fileName')
    lastModificationDateAfter = getValue(chosenOptions['after'],'lastModifiedDate')
    lastAddedDateAfter = getValue(chosenOptions['after'],'lastAddedDate')
    lastViewedDateAfter = getValue(chosenOptions['after'],'lastViewedDate')
    fileMineType = getValue(chosenOptions,'type')
    fileAddedByDevice = getValue(chosenOptions,'fileAddedBy')

    sentence += constructSentence('title',title)+constructSentence('lastModificationDateAfter',lastModificationDateAfter)+constructSentence('lastAddedDateAfter',lastAddedDateAfter)+constructSentence('lastViewedDateAfter',lastViewedDateAfter)+constructSentence('fileMineType',fileMineType)+constructSentence('fileAddedByDevice',fileAddedByDevice)
    sentence = sentence.slice(0,sentence.length-1)
    console.log '########'
    console.log(sentence)
    console.log(chosenOptions)
    console.log '########'
#    return false
    scope.search(null,null,sentence)
    $uibModalInstance.close(chosenOptions)
  $scope.cancel=()->
    chosenOptions['fileName']=$scope.fileName

    $uibModalInstance.close(chosenOptions)

.controller 'sharedFileModal', ($scope,Utils,ApiService,$translate, $uibModalInstance,file,$timeout,scope, CmisService)->
#  alert($('#qrcode').html())


  $scope.file = file
  if file.sharedLink
    $scope.hasSharedLink = true
    $scope.sharedLink = file.sharedLink
  else
    $scope.hasSharedLink = false

  $timeout(()->
    if !$('#qrcode').html() && $scope.sharedLink
      $('#qrcode').qrcode({width: 80,height: 80,text: $scope.sharedLink})
#    console.log($('.btn-clipboard'))
    $('#share-content').on('mouseleave','.btn-clipboard',()->
      $scope.tooltipIsOpen = false
#      console.log($scope.tooltipIsOpen)
      $timeout(()->
        $scope.$apply()
      )
    )
  ,0)
  #    g+  https://plus.google.com/share?url=
  #    facebook https://www.facebook.com/share.php?u=
  #    weibo http://service.weibo.com/share/share.php?url=
  #    tweet https://twitter.com/intent/tweet?text=
  onSuccess = (e)->
    $scope.copyResult = 'copy_success'
    $scope.tooltipIsOpen = true
    if !CmisService.isAndroid && !CmisService.isIOS
      e.clearSelection()
    $('.share-copy-link-tooiltip').removeClass('hide')
    $timeout(()->
      scope.$apply()
    )
    $timeout(()->
      $('.share-copy-link-tooiltip').addClass('hide')
    ,2000)
  onError = (e)->
    $scope.copyResult = 'press_cmd_c_to_copy'
    $scope.tooltipIsOpen = true
    $timeout(()->
      scope.$apply()
    )
  if CmisService.device == 'platform-pad'
    $scope.clickToShare = ()->
      cordova.plugins.clipboard.copy($scope.sharedLink,onSuccess,onError)
  else
    clipboard = new Clipboard('.btn-clipboard')
    clipboard.on('success', onSuccess)
    clipboard.on('error',onError)

  appSharedLink = {
    google:'https://plus.google.com/share?url='
    facebook:'https://www.facebook.com/share.php?u='
    twitter:'https://twitter.com/intent/tweet?text='
    linkedin:'https://www.linkedin.com/shareArticle?mini=true&url='
    weibo:'http://service.weibo.com/share/share.php?title='

  }
  $scope.loading=false
  $scope.getSharedFileLink = ()->
#    test
#    file.sharedLink='http:wwhadnwandkw.dwjadjwajdjwajda.com'
#    $scope.sharedLink='http:wwhadnwandkw.dwjadjwajdjwajda.com'
#    $scope.hasSharedLink = true
#    return false


    if $scope.loading
      return
    else
#      Utils.sendGaEvent("Document", "PublicShare", file.id)
      $scope.loading=true
      ApiService.getSharedFileLink(file,null,(sharedLink)->
        $scope.loading=false
        $scope.waitingForLink = false
        file.sharedLink = sharedLink
        file.description = {
          shareLink:sharedLink
        }
        $scope.sharedLink = file.sharedLink
        $scope.hasSharedLink = true
        $timeout(()->
          $scope.$apply()
        )
        Utils.waitForDomReady('#qrcode',
          ()->
#            success callback
            if !$('#qrcode').html()
              $('#qrcode').qrcode({width: 80,height: 80,text: $scope.sharedLink})
        ,
          ()->
#            error callback
        ,200,5000)
      ,
        (err)->
          $scope.loading=false
          Utils.warning(err)
          console.log err
          $timeout(()->
            $scope.$apply()
          )
      )

  if !file.sharedLink
    $scope.waitingForLink = true
    $scope.getSharedFileLink()

  $scope.getAppSharedApiLink = (appName)->
    appSharedLink[appName]
  $scope.shareTo = (appName)->
    appSharedApiLink = $scope.getAppSharedApiLink(appName)
    if CmisService.device == 'platform-pad'
      cordova.InAppBrowser.open(appSharedApiLink+$scope.sharedLink, '_blank', 'hidden=no')
    else
      window.open(
        appSharedApiLink+$scope.sharedLink
        appName
        "width=420,height=400,resizable,scrollbars=yes,status=1"
      )
    return true
  $scope.closeSharedLink = ()->
    if $scope.loading
      return
    else
      $scope.loading=true
      code = $scope.sharedLink.slice($scope.sharedLink.lastIndexOf('/')+1)
      ApiService.closeSharedLink(code,(data)->
        $scope.loading=false
        $scope.waitingForLink = false
        file.sharedLink = ''
        file.description = ''
        $scope.sharedLink = ''
        $scope.hasSharedLink = false
        if !$('#qrcode').html()
          $('#qrcode').qrcode({width: 80,height: 80,text: $scope.sharedLink})
        $timeout(()->
          $scope.$apply()
        )
      ,
        (err)->
          $scope.loading=false
          Utils.warning(err)
          $timeout(()->
            $scope.$apply()
          )
      )
#  $scope.showQR = ()->
#    if(!$('#qrcode').html())
#      $('#qrcode').qrcode({width: 80,height: 80,text: $scope.sharedLink});
#    $('.webchat-share-info').removeClass('hide')
#    $('.tri-angle-pointer').removeClass('hide')
#    return true
#  $scope.hideQR = ()->
#    $('.webchat-share-info').addClass('hide')
#    $('.tri-angle-pointer').addClass('hide')
#    return true
  $scope.ok = ()->
    $uibModalInstance.close()




